<?php
declare (strict_types = 1);

namespace app\index\controller;


use app\index\BaseController;
use think\Exception;
use app\index\model\Like as LikeModel;
use app\index\model\Article;
use think\facade\Log;

class Like extends BaseController
{
    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>['create','delete']],
        'access:@' => ['only'=>['create','delete']],
    ];

    //添加收藏
    public function create(int $article_id){
        try{

            //验证数据
            $article = $this->getModel(Article::class, $article_id);

            //获取收藏模型
            $likedModel = LikeModel::likedModel((int) $article->id);

            //如果已存在 抛异常
            if($likedModel && $likedModel->isExists()) throw new Exception('您已收藏.');

            //不存在 创建收藏记录
            $ret = $likedModel->save([
                'user_id' => app()->user->getId(),
                'article_id' => $article->id
            ]);

            if (!$ret) throw new Exception('收藏失败,请重试.');



            return json([
                'code' => 0,
                'msg' => '收藏成功.'
            ]);
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }


    }

    //删除收藏
    public function delete(int $article_id){
        try{

            //验证数据
            $article = $this->getModel(Article::class, $article_id);


            //获取收藏模型
            $likedModel = LikeModel::likedModel((int) $article->id);

            //如果已存在 抛异常
            if($likedModel && $likedModel->isEmpty()) throw new Exception('您未收藏.');

            $ret = $likedModel->delete() !== false;

            if (!$ret) throw new Exception('删除收藏失败.');


            return json([
                'code' => 0,
                'msg' => '删除收藏成功.'
            ]);
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }
    }

}
